package com.example.springcloudwinter.service;

import com.example.springcloudwinter.bo.OrderBo;
import com.example.springcloudwinter.dto.ResultEntity;
import com.example.springcloudwinter.mapper.PaymentMapper;
import com.example.springcloudwinter.po.OrderPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;


@Service
public class PaymentService {

    @Autowired
    private PaymentMapper paymentMapper;

    private static final int MAX_POINT = 500;

    public ResultEntity<?> payOrder (int orderId, String userId) {
        ResultEntity<?> result=new ResultEntity<>();
        OrderPo order;
        List<OrderPo> validPoints;
        try {
            validPoints = paymentMapper.getValidPoints(userId);
            order = paymentMapper.getOrderById(orderId, userId);
            if(order==null){
                result.setCode(601);
                return result;
            }else if(order.getOrderState()==1){
                result.setCode(602);
                return result;
            }

            //需要分离出来的积分操作
            int points = 0;
            double max = MAX_POINT > order.getOrderTotal()*100 ? MAX_POINT : order.getOrderTotal()*100;
            for (OrderPo orderEntity : validPoints) {
                points += orderEntity.getRemainingPoints();
                if (points >= MAX_POINT) {
                    orderEntity.setRemainingPoints(points - MAX_POINT);
                    paymentMapper.updatePoints(orderEntity.getOrderId(), orderEntity.getRemainingPoints());
                    break;
                }
                else {
                    paymentMapper.updatePoints(orderEntity.getOrderId(), 0);
                }
            }
            //

            if(paymentMapper.payOrder(orderId, userId)<=0)return result;
            else {
                result.setCode(200);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}
